import axios, { AxiosInstance } from 'axios';
import { NetworkOptions, LanguagePackage } from '../types';
import { logger } from '../../utils/logger';

export class NetworkManager {
  private client: AxiosInstance;
  private options: NetworkOptions;

  constructor(options: NetworkOptions) {
    this.options = options;
    this.client = axios.create({
      baseURL: options.baseUrl,
      timeout: options.timeout || 5000,
      headers: options.headers
    });
  }

  /**
   * 下载语言包
   * @param language 语言代码
   * @param url 下载地址
   */
  public async downloadLanguage(language: string, url: string): Promise<LanguagePackage | null> {
    try {
      logger.info('开始下载语言包', { language, url });

      const response = await this.client.get(url);
      if (response.status !== 200 || !response.data) {
        logger.warn('语言包下载失败', { language, status: response.status });
        return null;
      }

      // 转换响应数据为LanguagePackage格式
      const data = response.data;
      const translations = new Map<string, string>();

      // 处理不同格式的响应数据
      if (typeof data === 'object') {
        if (data.data) {
          // 标准格式
          Object.entries(data.data).forEach(([key, value]) => {
            translations.set(key, value as string);
          });
        } else {
          // 扁平格式
          Object.entries(data).forEach(([key, value]) => {
            translations.set(key, value as string);
          });
        }
      }

      const languagePackage: LanguagePackage = {
        language,
        data: translations,
        version: data.version
      };

      logger.info('语言包下载成功', { 
        language, 
        translationCount: translations.size 
      });

      return languagePackage;
    } catch (error) {
      logger.error('语言包下载出错', { 
        language, 
        error: error instanceof Error ? error.message : String(error) 
      });
      return null;
    }
  }

  /**
   * 获取支持的语言列表
   */
  public async getLanguages(): Promise<Array<{ language: string; name: string; path: string }>> {
    try {
      const response = await this.client.get('/languages');
      if (response.status === 200 && response.data) {
        return response.data.language || [];
      }
      return [];
    } catch (error) {
      logger.error('获取语言列表失败', { 
        error: error instanceof Error ? error.message : String(error) 
      });
      return [];
    }
  }
} 